package com.sojson.util.encryption;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.sojson.constant.Constant;
import com.sojson.util.encryption.enums.EEncryptionType;

/**
 * HMAC-SHA256加密解密工具类
 * 
 * @author liu
 * @date 2020-09-04
 */
public class Hmacsha256Util {

    private Hmacsha256Util() {}

    /**
     * 加密
     * 
     * @param content   内容
     * @param key       (微信商户密钥(API密钥)...)
     * @return
     * @throws Exception
     */
    public static String encryption(String content, String key) throws Exception {
        return encryption(content.getBytes(Constant.DEFAULT_ENCODING), key.getBytes(Constant.DEFAULT_ENCODING));
    }

    /**
     * 加密
     * 
     * @param content   内容
     * @param key       (微信商户密钥(API密钥)...)
     * @return
     * @throws Exception
     */
    public static String encryption(byte[] content, byte[] key) throws Exception {
        String type = EEncryptionType.HMACS_HA256.getType();
        Mac sha256_HMAC = Mac.getInstance(type);
        SecretKeySpec secret_key = new SecretKeySpec(key, type);
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(content);
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }

    /**
     * 加密并转为大写
     * 
     * @param content   内容
     * @param key       (微信商户密钥(API密钥)...)
     * @return
     * @throws Exception
     */
    public static String encryptionToUpperCase(String content, String key) throws Exception {
        return encryption(content, key).toUpperCase();
    }

    /**
     * 加密并转为大写
     * 
     * @param content   内容
     * @param key       (微信商户密钥(API密钥)...)
     * @return
     * @throws Exception
     */
    public static String encryptionToUpperCase(byte[] content, byte[] key) throws Exception {
        return encryption(content, key).toUpperCase();
    }

}